package com.zto.wk.webflux.router;

import com.zto.wk.webflux.handler.EchoHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by wangkuan at 2018-08-02 15:20
 */
@Configuration
public class WebSocketRouter {

    @Bean
    public HandlerMapping webSocketMapping(EchoHandler handler) {
        //使用 map 指定 WebSocket 协议的路由，路由为 ws://localhost:8080/echo
        final Map<String, WebSocketHandler> urlMap = new HashMap<>();
        urlMap.put("/echo", handler);

        //SimpleUrlHandlerMapping 指定了 WebSocket 的路由配置
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setOrder(Ordered.HIGHEST_PRECEDENCE);
        mapping.setUrlMap(urlMap);

        return mapping;
    }

    /**
     * WebSocketHandlerAdapter 负责将 EchoHandler 处理类适配到 WebFlux 容器中
     */
    @Bean
    public WebSocketHandlerAdapter handlerAdapter() {
        return new WebSocketHandlerAdapter();
    }
}
